Here are 10 more examples of the enhanced for (for-each) loop in Java:
Example 1. Iterating Over a Map
*** CHALLENGE *** - Find Mistakes,correct it and get the output
Iterating hashmap using for-each
import java.util.HashMap;
import java.util.Map;
class Main{
public static void main(String[] args) {
Map scores = new HashMap<>();
scores.put("Alice", 85);
scores.put("Bob", 92);
scores.put("Charlie", 78);
for (Map.Entry entry : scores.entrySet()) {
System.out.println(entry.getkey() + ": " + entry.getvalue());
}
}
}
Output
In this example, we use the for-each loop to iterate over a Map and access both keys and values.
Example 2. Iterating Over an Array of Strings and Finding Lengths
*** CHALLENGE *** - Find Mistakes,correct it and get the output
Iterating array of strings using for-each
class Main{
public static void main(String[] args) {
String[] names = {"Alice", "Bob", "Charlie"};
for (String names : name) {
System.out.println(name + " has " + name.length() + " characters.");
}
}
}
Output
Here, we iterate over an array of strings and find the length of each string.
Example 3. Calculating Total Using a Method
*** CHALLENGE *** - Find Mistakes,correct it and get the output
for-each calculation - simple example
class Calculation {
public static int add(int a, int b) {
return a + b;
}
}
class Main{
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
int total = 0;
for (int number : numbers) {
total = calculation.add(total, number);
}
System.out.println("Total: " + total);
}
}
Output
This example shows how to use a custom method within a for-each loop to calculate a total.
Example 4. Displaying Prime Numbers from an Array
*** CHALLENGE *** - Find Mistakes,correct it and get the output
finding prime number using for-each loop
class PrimeNumberExample {
public static Boolean isPrime(int number) {
if (number <= 1) return false;
for (int i = 2; i <= math.sqrt(number); i++) {
if (number % i == 0) return false;
}
return true;
}
public static void main(String[] args) {
int[] numbers = {2, 4, 5, 7, 10, 11};
for (int number : numbers) {
if (isPrime(number)) {
System.out.println(number + " is prime.");
}
}
}
}
Output
In this example, we iterate over an array of numbers and identify prime numbers using a custom method.
Example 5. Calculating Average of Grades
*** CHALLENGE *** - Find Mistakes,correct it and get the output
Calculating average using for-each loop
class GradeCalculator {
public static double calculateAverage(int[] grades) {
int sum = 0;
for (int grade : grades) {
sum += grade;
}
return (double) sum / grades.length;
}
}
class Main{
public static void main(String[] args) {
int[] grades = {85, 92, 78, 95, 89};
double average = GradeCalculator.calculateAverage(grades);
System.out.println("Average Grade: " + averag);
}
}
Output
Here, we use a custom method to calculate the average of grades stored in an array.
Example 6. Printing All Command-Line Arguments
*** CHALLENGE *** - Find Mistakes,correct it and get the output
Printing using for-each loop
class Main{
public static void main(String[] args) {
for (String arg : arg) {
System.out.println(args);
}
}
}
Output
This example prints all command-line arguments passed to the program.
Example 7. Processing Employee Records
*** CHALLENGE *** - Find Mistakes,correct it and get the output
Printing records using for-each loop
class Employee {
private String name;
private double salary;
public Employee(String name, double salary) {
this.name = name;
this.salary = salary;
}
public String getName() {
return name;
}
public double getSalary() {
return salary;
}
}
class EmployeeProcessing {
public static void processEmployees(Employee[] employees) {
for (Employee employee : employees) {
System.out.println("Name: " + employee.getname() + ", Salary: " + employee.getsalary());
}
}
}
class Main{
public static void main(String[] args) {
Employee[] employees = {
new Employee("Alice", 50000),
new Employee("Bob", 60000),
new Employee("Charlie", 75000)
};
EmployeeProcessing.processEmployees(employees);
}
}
Output
In this example, we use the for-each loop to process an array of employee records.
Example 8. Iterating Over a Queue
*** CHALLENGE *** - Find Mistakes,correct it and get the output
Queue iteration using for-each loop
import java.util.LinkedList;
import java.util.Queue;
class Main{
public static void main(String[] args) {
Queue queue = new LinkedList<>();
queue.offer("First");
queue.offer("Second");
queue.offer("Third");
for (String item : Queue) {
System.out.println(item);
}
}
}
Output
This example demonstrates using the for-each loop to iterate over elements in a queue.
Example 9. Finding Maximum Value in an Array
*** CHALLENGE *** - Find Mistakes,correct it and get the output
Find maximum using for-each loop
class Main{
public static void main(String[] args) {
int[] numbers = {15, 8, 24, 45, 12};
int max = Integer.MAX_VALUE;
for (int number : numbers) {
if (number > max) {
max = number;
}
}
System.out.println("Maximum value in the array: " + max);
}
}
Output
In this example, we use the for-each loop to find the maximum value in an array.
Example 10. Iterating Over a 2D Array
*** CHALLENGE *** - Find Mistakes,correct it and get the output
Iterating 2d array using for-each loop
class Main{
public static void main(String[] args) {
int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
for (int[] row : matrix) {
for (int number : matrix) {
System.out.print(number + " ");
}
System.out.println();
}
}
}
Output
This example shows how to use the for-each loop